package com.ray.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ray.bean.FeedOrderDetailBean;
import com.ray.bean.OrderBean;
import com.ray.bean.OrderCustomTagBean;
import com.ray.bean.OrderInfoDetailBean;
import com.ray.bean.OrderInfoDetailSourceAndApplyBean;
import com.ray.bean.OrderInfoTemplateBean;
import com.ray.bean.ReportBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.BasicDataMapper;
import com.ray.mapper.FileManagerMapper;
import com.ray.mapper.OrderCreateApplyMapper;
import com.ray.mapper.OrderCreateMapper;
import com.ray.mapper.OrderMapper;
import com.ray.util.ArrayUtils;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.validate.ValidateUtils;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;
/**
 * 
 * @author Shensg
 * 2018年1月26日
 */
@Service
public class OrderCreateApplyService {
	@Autowired
	OrderCreateApplyMapper orderCreateMapper;
	@Autowired
	OrderCreateMapper orderCreateMapperNoApply;
	@Autowired
	BasicDataMapper basicDataMapper;
	@Autowired
	WeiXinService weiXinService;
	@Autowired
	FileManagerMapper fileManagerMapper;
	@Autowired
	WeChatToMessageService weChatToMessageService;
	@Autowired
	OrderMapper orderMapper;
	@Autowired
	WorkshopService workshopService;
	@Autowired
	OrderService orderService;
	@Autowired
	PurchaseOrderService purchaseOrderService;
	@Autowired
	FeedOrderService feedOrderService;
	
	public List<Map> getOrderTabList(Map map) {
		String type = map.get("type").toString();
		if("1".equals(type)) {
			map.remove("type");
			map.put("type","原材料仓");
			//return basicDataMapper.getOrderTabList(map);
			return basicDataMapper.getOrderTabListForSourceFactory(map);
		}
		if("2".equals(type)) {
			map.remove("type");
			map.put("type","辅料仓");
			return basicDataMapper.getOrderTabList(map);
		}
		if("3".equals(type)) {
			map.remove("type");
			map.put("type","信息备注仓");
			return basicDataMapper.getOrderTabList(map);
		}
		return orderCreateMapper.getOrderTabList(map);
	}

	public List<Map> getFactoryTabChildList(Map<String, String> map) {
		// TODO Auto-generated method stub
		if("1".equals(map.get("material_factory"))){
			map.remove("material_factory");
			map.put("material_factory","原材料仓");
		}
		if("2".equals(map.get("material_factory"))){
			map.remove("material_factory");
			map.put("material_factory","原材料仓,辅料仓");
		}
		if("3".equals(map.get("material_factory"))){
			map.remove("material_factory");
			map.put("material_factory","信息备注仓");
		}
		return orderCreateMapper.getFactoryTabChildList(map);
	}
	//保存html 模版
	public int saveAsOrderTemplate(OrderInfoTemplateBean bean) {
		// TODO Auto-generated method stub
		return orderCreateMapper.saveAsOrderTemplate(bean);
	}
	//获取基础数据列表
	public List<Map> getDataBasicList(Map map) {
		// TODO Auto-generated method stub
		return orderCreateMapper.getDataBasicList(map);
	}

	public void updateDataBasicById(Map map) {
		// TODO Auto-generated method stub
		String str = map.get("html_type_val").toString().replaceAll("，", ",");
		map.put("html_type_val", str);
		orderCreateMapper.updateDataBasicById(map);
	}
	
	//保存订单信息
	public boolean saveOrderInfo(Map map) throws ServiceException {
		String save_as_new_order=map.get("save_as_new_order").toString();
		String order_no = map.get("order_p_order_no").toString();
		if("1".equals(save_as_new_order)) {
			order_no=(String) orderCreateMapper.getOrderInfoFixed(map).get("result");
			fileManagerMapper.updateLastOneOrderNoByUserName(order_no,map);
		}
		map.put("order_p_order_no",order_no);
		
		/*校验是否有申请中的数据*/
		List<Map<String, String>> listMyApply = orderCreateMapperNoApply.getMyApplyInfo(order_no);
		if(listMyApply.size()>0) {
			throw new ServiceException("订单已经申请,请勿重复提交\r\n" +
    		  		"申请人["+listMyApply.get(0).get("apply_user")+"] 申请时间["+listMyApply.get(0).get("apply_time")+"]");
		}
		
		if(map.get("order_p_audit")!=null) {
			if("true".equals(map.get("order_p_audit").toString())) {
				map.put("order_p_audit", "1");
			}else {
				map.put("order_p_audit", "0");
			}
		}
		if(map.get("order_p_order_no_comp")!=null) {
			//客户订单编号 如果没有 和订单编号一样 ，有取自己的
			if("".equals(map.get("order_p_order_no_comp").toString().trim())) {
				map.put("order_p_order_no_comp", order_no);
			}
		}
		//订单提交 审核不选 订单状态默认计划
		map.put("order_p_order_status", "计划");
		map.put("order_p_audit", "0");
		
		map.put("audit_type", "1");//生产订单审核 项目为1 
		/*if(orderCreateMapper.checkAuditTheSameOne(map)>0) {
			map.put("order_p_order_status", "审核");
			map.put("order_p_audit", "1");
		}*/
		
		String order_template_id = map.get("order_template_id").toString();
		//制单人
		if(map.get("order_p_created")==null||map.get("order_p_created").toString().trim().length()<1) {
			map.put("order_p_created", map.get("loginUserName"));
		}
		//保存生产订单主表
		int id_primary = orderCreateMapper.saveOrderInfo(map);
		//保存生产订单明细表
		List<OrderInfoDetailBean> list_orderDetails = getOrderInfoDetailBean(map,order_no);
		//保存自定义表单
		List<OrderCustomTagBean> list_orderCustomTag = getOrderCustomTagBean(map,order_no);
		
		//保存生产订单明细表 数据过大拆分
		List<OrderInfoDetailBean> list_orderDetails_new= new ArrayList<>();
		for (int i = 0; i < list_orderDetails.size(); i++) {
			list_orderDetails_new.add(list_orderDetails.get(i));
			if(list_orderDetails_new.size()==20) {//每20条数据拆分
				int id_detail = orderCreateMapper.saveOrderInfoDetail(list_orderDetails_new);
				list_orderDetails_new.clear();
			}
		}
		if(list_orderDetails_new.size()>0) {//如果少于20条
			int id_detail = orderCreateMapper.saveOrderInfoDetail(list_orderDetails_new);
			list_orderDetails_new.clear();
		}
		
		//保存生产订单明细-tail表
		List<OrderInfoDetailBean> list_orderTails = getOrderInfoTailBean(map,order_no);
		int id_tail = orderCreateMapper.saveOrderInfoTail(list_orderTails);
		//如果有data_classification 则使用分类仓保存
		List<OrderInfoDetailBean> list_data_classification = getOrderInfoTailBeanClassification(map,order_no);
		orderCreateMapper.saveOrderInfoTail(list_data_classification);
		//当投料数大于0保存一份到order_info_detail
		orderCreateMapper.saveOrderInfoDetailFromTail(order_no,map.get("apply_id").toString(),map.get("order_p_order_total").toString());		
		//保存自定义标签
		int id_customTag = orderCreateMapper.saveOrderCustomTag(list_orderCustomTag);
		//保存模版和订单编号
		if(Integer.valueOf(order_template_id)!=0) {
			int id_order_template = orderCreateMapper.saveOrderInfoAndTemplate(order_no,order_template_id,map.get("apply_id").toString());
		}
		//插入companyMaterial 不再保存20180404
		/*for(OrderInfoDetailBean bean:list_orderDetails) {
			if(bean.getMaterialFactory()=="1") {
				bean.setMaterialFactory("原材料仓");
			}else if(bean.getMaterialFactory()=="2") {
				bean.setMaterialFactory("辅料仓");
			}else {
				bean.setMaterialFactory("信息备注仓");
			}
			bean.setCompany(map.get("loginCompany").toString());
			if(bean.getMaterialCode()!=null&&bean.getMaterialCode().trim().length()!=0) {//有code insert into select
				orderCreateMapper.insertCompanyMTbyCode(bean.getMaterialCode(),bean.getCompany());
			}else {
				orderCreateMapper.insertCompanyMTbyBean(bean);
			}
		}
		for(OrderInfoDetailBean bean:list_orderTails) {
			if(bean.getMaterialFactory()=="1") {
				bean.setMaterialFactory("原材料仓");
			}else if(bean.getMaterialFactory()=="2") {
				bean.setMaterialFactory("辅料仓");
			}else {
				bean.setMaterialFactory("信息备注仓");
			}
			bean.setCompany(map.get("loginCompany").toString());
			if(bean.getMaterialCode()!=null&&bean.getMaterialCode().trim().length()!=0) {//有code insert into select
				orderCreateMapper.insertCompanyMTbyCode(bean.getMaterialCode(),bean.getCompany());
			}else {
				orderCreateMapper.insertCompanyMTbyBean(bean);
			}
		}*/
		return true;
	}
	
	//获取自定义表单信息数据 组装 当前只有一条数据
	private List<OrderCustomTagBean> getOrderCustomTagBean(Map map, String order_no) {
		List<OrderCustomTagBean> list = new ArrayList<>();
		OrderCustomTagBean bean =new OrderCustomTagBean();
		if(map.get("order_label_label_val")!=null) {
			bean.setLabel(map.get("order_label_label_val").toString());
		}
		if(map.get("order_label_table_val")!=null) {
			bean.setTable(map.get("order_label_table_val").toString());
		}
		if(map.get("order_label_table_val_two")!=null) {
			bean.setTableTwo(map.get("order_label_table_val_two").toString());
		}
		if(map.get("order_label_table_val_three")!=null) {
			bean.setTableThree(map.get("order_label_table_val_three").toString());
		}
		if(map.get("order_label_table_val_four")!=null) {
			bean.setTableFour(map.get("order_label_table_val_four").toString());
		}
		if(map.get("order_label_table_val_five")!=null) {
			bean.setTableFive(map.get("order_label_table_val_five").toString());
		}
		//6
		if(map.get("order_label_table_val_six")!=null) {
			bean.setTableSix(map.get("order_label_table_val_six").toString());
		}
		//7
		if(map.get("order_label_table_val_seven")!=null) {
			bean.setTableSeven(map.get("order_label_table_val_seven").toString());
		}
		//8
		if(map.get("order_label_table_val_eight")!=null) {
			bean.setTableEight(map.get("order_label_table_val_eight").toString());
		}
		//9
		if(map.get("order_label_table_val_nine")!=null) {
			bean.setTableNine(map.get("order_label_table_val_nine").toString());
		}
		//10
		if(map.get("order_label_table_val_ten")!=null) {
			bean.setTableTen(map.get("order_label_table_val_ten").toString());
		}
		bean.setOrderNo(order_no);
		bean.setApplyId(map.get("apply_id").toString());
		list.add(bean);
		return list;
	}

	//获取订单明细尾巴Tail表
	private List<OrderInfoDetailBean> getOrderInfoTailBean(Map map, String orderNo) {
		List<OrderInfoDetailBean> list = new ArrayList<>();
		OrderInfoDetailBean bean = null;
		if(map.get("order_s_input_material_house")==null) {
			return list;
		}
		String[] materialHouse = map.get("order_s_input_material_house").toString().split(",");
		String[] materialType=map.get("order_s_input_material_type").toString().split(",");
		String[] materialModel=map.get("order_s_input_val_material_type").toString().split(",");
		String[] materialCode=map.get("order_s_input_material_code").toString().split(",");
		String[] feedTotal=null;
		if(map.get("order_s_input_val_feed_total")!=null)feedTotal=map.get("order_s_input_val_feed_total").toString().split(",");
		//工艺
		String[] arts=null;
		if(map.get("order_s_input_val_arts")!=null)arts=map.get("order_s_input_val_arts").toString().split(",");
		//材质
		String[] qualityType=null;
		if(map.get("order_s_input_val_quality_type")!=null)qualityType=map.get("order_s_input_val_quality_type").toString().split(",");
		//读取颜色 //20190330 去除模板控制物料类型
		/*String[] isReadColor=null;
		if (map.get("order_s_input_isReadColor")!=null) {
			isReadColor=map.get("order_s_input_isReadColor").toString().split(",");
		}*/
		//读取说明
		String[] remark=null;
		if (map.get("order_s_input_val_remark")!=null) {
			remark=map.get("order_s_input_val_remark").toString().split(",");
		}
		//读取供应商
		String[] providerName=null;
		if (map.get("order_s_input_val_provider_name")!=null) {
			providerName=map.get("order_s_input_val_provider_name").toString().split(",");
		}
		for(int i=0;i<materialType.length;i++) {
			bean = new OrderInfoDetailBean();
			bean.setMaterialFactory(materialHouse[i]);
			bean.setMaterialType(materialType[i]);
			//20190330 去除模板控制物料类型
			/*if (isReadColor!=null&&isReadColor[i].trim().length()>0) {
				bean.setIsReadColor(Integer.valueOf(isReadColor[i]));
			}*/
			//校验是否为0 避免新模板保存的时候出现的问题
			if(bean.getIsReadColor()==0) {
				map.put("material_type", bean.getMaterialType());
				map.put("material_factory", bean.getMaterialFactory());
				Map<String, String> materialTypeInfo = orderCreateMapperNoApply.getMaterialTypeInfo(map);
				bean.setIsReadColor(Integer.valueOf(materialTypeInfo.get("isReadColor")));
			}
			bean.setOrderNo(orderNo);
			bean.setMaterialModel(materialModel[i]);
			bean.setMaterialCode(materialCode[i].trim());
			bean.setApplyId(map.get("apply_id").toString());
			if(feedTotal!=null) {
				bean.setFeedTotal((feedTotal[i].trim().length()>0)?feedTotal[i].trim():"0");//投料数
			}
			if(arts!=null) {
				bean.setArts((arts[i].trim().length()>0)?arts[i].trim():"");//投料数
			}
			if(qualityType!=null) {
				bean.setQualityType((qualityType[i].trim().length()>0)?qualityType[i].trim():"");//投料数
			}
			if(remark!=null) {
				bean.setRemark((remark[i].trim().length()>0)?remark[i].trim():"");//说明
			}
			if(providerName!=null) {
				bean.setProviderName((providerName[i].trim().length()>0)?providerName[i].trim():"");//说明
			}
			//获取物料信息
			OrderInfoDetailBean beanByCode = orderCreateMapperNoApply.getMaterialInfoByCode(bean.getMaterialCode(),map);
			if(beanByCode!=null) {
				bean.setMaterialCode(beanByCode.getMaterialCode());//物料代码
				if(1==bean.getIsReadColor()) {
					if (bean.getIsReadColor()==0) {
						bean.setIsReadColor(1);
					}
					bean.setColor(beanByCode.getColor());//色号
					bean.setColorDescription(beanByCode.getColorDescription());//描述
				}else {
					if (bean.getIsReadColor()==0) {
						bean.setIsReadColor(2);
					}
				}
				bean.setMaterialModel(beanByCode.getMaterialModel());//规格
				bean.setMaterialName(beanByCode.getMaterialName());//物料名称
			}
			list.add(bean);
		}
		return list;
	}
	//获取订单明细尾巴Tail表
		private List<OrderInfoDetailBean> getOrderInfoTailBeanClassification(Map map, String orderNo) {
			List<OrderInfoDetailBean> list = new ArrayList<>();
			OrderInfoDetailBean bean = null;
			net.sf.json.JSONArray json = net.sf.json.JSONArray.fromObject(map.get("data_classification") ); // 首先把字符串转成 JSONArray  对象
			if(json.size()>0){
			  for(int i=0;i<json.size();i++){
				bean = new OrderInfoDetailBean();
				net.sf.json.JSONObject job = json.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
				bean.setOrderNo(orderNo);
				bean.setMaterialType(job.has("material_type")?job.getString("material_type"):null);
				bean.setMaterialModel(job.has("material_model")?job.getString("material_model"):null);
				bean.setMaterialFactory(job.has("material_factory")?job.getString("material_factory"):null);
				bean.setMaterialCode(job.has("material_code")?job.getString("material_code"):null);
				bean.setFeedTotal(job.has("feed_total")?(job.getString("feed_total").length()>0?job.getString("feed_total"):"0"):"0");
				bean.setMaterialName(job.has("material_name")?job.getString("material_name"):null);
				bean.setColor(job.has("color")?job.getString("color"):null);
				bean.setColorDescription(job.has("color_description")?job.getString("color_description"):null);
				bean.setArts(job.has("arts")?job.getString("arts"):null);
				bean.setQualityType(job.has("quality_type")?job.getString("quality_type"):null);
				bean.setIsReadColor(1);
				bean.setRemark(job.has("remark")?job.getString("remark"):null);
				bean.setProviderName(job.has("provider_name")?job.getString("provider_name"):null);
				bean.setClassification(job.has("classification")?job.getString("classification"):null);
				bean.setApplyId(map.get("apply_id").toString());
				list.add(bean);
			  }
			}
			return list;
		}
	//获取订单明细Bean
	private List<OrderInfoDetailBean> getOrderInfoDetailBean(Map map,String orderNo) {
		Map<String, String> lineNoCodeMap = getLineNoCode(map);
		List<OrderInfoDetailBean> list = new ArrayList<>();
		OrderInfoDetailBean bean = null;
		if(map.get("order_s_table_source_arr_str")==null||map.get("order_s_line_no")==null) {
			return list;
		}
		/*投料数*/
		String[] feedTotal = null;
		if(map.get("order_s_feed_total")!=null)feedTotal=map.get("order_s_feed_total").toString().split(",");
		/*行号*/
		String[] lineNo	= map.get("order_s_line_no").toString().split(",");
		/*物料代码*/
		String[] materialCode	= null;
		if(map.get("order_s_material_code")!=null)materialCode=map.get("order_s_material_code").toString().split(",");
		/*色号*/
		String[] materialColor= null;
		if(map.get("order_s_material_color")!=null)materialColor=map.get("order_s_material_color").toString().split(",");
		/*色号描述*/
		String[] materialColorDescription = null;
		if(map.get("order_s_material_description")!=null)materialColorDescription=map.get("order_s_material_description").toString().split(",");
		/*规格*/
		String[] materialModel=null;
		if(map.get("order_s_material_model")!=null)materialModel= map.get("order_s_material_model").toString().split(",");
		/*物料名称*/
		String[] materialName=null;
		if(map.get("order_s_material_name")!=null)materialName= map.get("order_s_material_name").toString().split(",");
		/*物料类型*/
		String[] materialType=null;
		if(map.get("order_s_material_type")!=null) materialType	=map.get("order_s_material_type").toString().split(",");
		/*订单数*/
		String[] orderTotal	= null;
		if(map.get("order_s_order_total")!=null)orderTotal=map.get("order_s_order_total").toString().split(",");
		/*物料所属仓*/
		String[] materialFactory=null;
		if(map.get("order_s_material_house")!=null)materialFactory=map.get("order_s_material_house").toString().split(",");

		/*每列有几个子列*/
		String[] tableSourceArr	=null;
		if(map.get("order_s_table_source_arr")!=null)tableSourceArr=map.get("order_s_table_source_arr").toString().split(",");
		/*order_s_mtlkt_total	每条料可开数*/
		String[] mtlktTotal	=null;
		if(map.get("order_s_mtlkt_total")!=null)mtlktTotal=map.get("order_s_mtlkt_total").toString().split(",");
		/*order_s_klfs_way	开料方式*/
		String[] klfsWay	=null;
		if(map.get("order_s_klfs_way")!=null)klfsWay=map.get("order_s_klfs_way").toString().split(",");
		/*order_s_ylts_total	用料条数*/
		String[] yltsTotal	=null;
		if(map.get("order_s_ylts_total")!=null)yltsTotal=map.get("order_s_ylts_total").toString().split(",");
		/*order_s_klcc_size	开料尺寸*/
		String[] klccSize	=null;
		if(map.get("order_s_klcc_size")!=null)klccSize=map.get("order_s_klcc_size").toString().split(",");
		/*order_s_small_order_total	每列订单数*/
		String[] smallOrderTotal	=null;
		if(map.get("order_s_small_order_total")!=null)smallOrderTotal=map.get("order_s_small_order_total").toString().split(",");
		/*order_s_small_feed_total	每列投料数*/
		String[] smallFeedTotal	=null;
		if(map.get("order_s_small_feed_total")!=null)smallFeedTotal=map.get("order_s_small_feed_total").toString().split(",");
		//拼料颜色
		String[] plys=null;
		if(map.get("order_s_plys")!=null)plys=map.get("order_s_plys").toString().split(",");
		//SKU号
		String[] skuNo=null;
		if(map.get("order_s_sku_no")!=null)skuNo=map.get("order_s_sku_no").toString().split(",");
		//单只条码贴
		String[] singleCode=null;
		if(map.get("order_s_single_code")!=null)singleCode=map.get("order_s_single_code").toString().split(",");
		//内盒商品标识贴
		String[] nhspCode=null;
		if(map.get("order_s_nhsp_code")!=null)nhspCode=map.get("order_s_nhsp_code").toString().split(",");
		//外箱商品标识贴
		String[] wxspCode=null;
		if(map.get("order_s_wxsp_code")!=null)wxspCode=map.get("order_s_wxsp_code").toString().split(",");
		//客户PO号
		String[] custPoNo=null;
		if(map.get("order_s_cust_po_no")!=null)custPoNo=map.get("order_s_cust_po_no").toString().split(",");
		//说明
		String[] remark=null;
		if(map.get("order_s_remark")!=null)remark=map.get("order_s_remark").toString().split(",");
		//镜片材质
		String[] glassesType=null;
		if(map.get("order_s_glasses_type")!=null)glassesType=map.get("order_s_glasses_type").toString().split(",");
		//透光率
		String[] lightTrans=null;
		if(map.get("order_s_light_trans")!=null)lightTrans=map.get("order_s_light_trans").toString().split(",");
		//位置
		String[] location=null;
		if(map.get("order_s_location")!=null)location=map.get("order_s_location").toString().split(",");
		//颜色
		String[] otherColor=null;
		if(map.get("order_s_other_color")!=null)otherColor=map.get("order_s_other_color").toString().split(",");
		//内容
		String[] content=null;
		if(map.get("order_s_content")!=null)content=map.get("order_s_content").toString().split(",");
		//尺寸
		String[] size=null;
		if(map.get("order_s_size")!=null)size=map.get("order_s_size").toString().split(",");
		//材质
		String[] qualityType=null;
		if(map.get("order_s_quality_type")!=null)qualityType=map.get("order_s_quality_type").toString().split(",");
		//字体
		String[] font=null;
		if(map.get("order_s_font")!=null)font=map.get("order_s_font").toString().split(",");
		//工艺
		String[] arts=null;
		if(map.get("order_s_arts")!=null)arts=map.get("order_s_arts").toString().split(",");
		//点漆色
		String[] dqs=null;
		if(map.get("order_s_dqs")!=null)dqs=map.get("order_s_dqs").toString().split(",");
		//烫印色
		String[] tys=null;
		if(map.get("order_s_tys")!=null)tys=map.get("order_s_tys").toString().split(",");
		//印字色
		String[] yzs=null;
		if(map.get("order_s_yzs")!=null)yzs=map.get("order_s_yzs").toString().split(",");
		//读取颜色 //20190330 去除模板控制物料类型
		/*String[] isReadColor=null;
		if (map.get("order_s_isReadColor")!=null) {
			isReadColor=map.get("order_s_isReadColor").toString().split(",");
		}*/
		//大货日期  special_dh_date
		String[] special_dh_date=null;
		int specialDhDateLength=0;//大货时间数量 特殊处理
		int specialDhDateLengthIndex=0;//当前大货下标
		if (map.get("special_dh_date")!=null) {
			special_dh_date=map.get("special_dh_date").toString().split("&");
			specialDhDateLength=special_dh_date.length;
		}
		//大货数量  order_s_dh_total
		String[] order_s_dh_total=null;
		if (map.get("order_s_dh_total")!=null) {
			order_s_dh_total=map.get("order_s_dh_total").toString().split(",");
		}
		String order_s_table_source_arr_str=map.get("order_s_table_source_arr_str").toString();
		List<List<String[]>> listArrStrList=ArrayUtils.arrayStrToArrayObj(order_s_table_source_arr_str);
		boolean addlist=true;
		for(int materialTypeIndex=0;materialTypeIndex<listArrStrList.size();materialTypeIndex++) {
			List<String[]> listArrStr = listArrStrList.get(materialTypeIndex);
			for (int i = 0; i < lineNo.length; i++) { //几行
				for (int j = 0; j < listArrStr.size(); j++) { //每列
					bean = new OrderInfoDetailBean();
					for (int j2 = 0; j2 < listArrStr.get(j).length; j2++) {//有几个小列
						switch (listArrStr.get(j)[j2].replaceAll("'", "")) {//每个小列是什么
							case "order_s_material_color"://有色号就有code
								bean.setColor(materialColor[0].trim());materialColor=ArrayUtils.delete(0, materialColor);
								bean.setMaterialCode(materialCode[0].trim());materialCode=ArrayUtils.delete(0, materialCode);	
								break;
							case "order_s_material_description":
								bean.setColorDescription(materialColorDescription[0].trim());materialColorDescription=ArrayUtils.delete(0, materialColorDescription);
								break;
							case "order_s_material_model":
								bean.setMaterialModel(materialModel[0].trim());materialModel=ArrayUtils.delete(0, materialModel);
								break;
							case "order_s_material_name":
								bean.setMaterialName(materialName[0].trim());materialName=ArrayUtils.delete(0, materialName);
								break;
							case "order_s_mtlkt_total":
								bean.setMtlktTotal(mtlktTotal[0]);mtlktTotal=ArrayUtils.delete(0, mtlktTotal);
								break;
							case "order_s_klfs_way":
								bean.setKlfsWay(klfsWay[0]);klfsWay=ArrayUtils.delete(0, klfsWay);
								break;
							case "order_s_small_order_total":
								if(smallOrderTotal[0].trim().length()==0) {
									bean.setSmallOrderTotal(null);smallOrderTotal=ArrayUtils.delete(0, smallOrderTotal);
								}else {
									bean.setSmallOrderTotal(smallOrderTotal[0]);smallOrderTotal=ArrayUtils.delete(0, smallOrderTotal);
								}
								break;
							case "order_s_small_feed_total":
								if(smallFeedTotal[0].trim().length()==0) {
									bean.setSmallFeedTotal(null);smallFeedTotal=ArrayUtils.delete(0, smallFeedTotal);
								}else {
									bean.setSmallFeedTotal(smallFeedTotal[0]);smallFeedTotal=ArrayUtils.delete(0, smallFeedTotal);
								}
								break;
							case "order_s_klcc_size":
								bean.setKlccSize(klccSize[0]);klccSize=ArrayUtils.delete(0, klccSize);
								break;
							case "order_s_ylts_total":
								bean.setYltsTotal(yltsTotal[0]);yltsTotal=ArrayUtils.delete(0, yltsTotal);
								break;
							case "order_s_plys":
								bean.setPlys(plys[0]);plys=ArrayUtils.delete(0, plys);
								break;
							case "order_s_sku_no":
								bean.setSkuNo(skuNo[0]);skuNo=ArrayUtils.delete(0, skuNo);
								break;
							case "order_s_single_code":
								bean.setSingleCode(singleCode[0]);singleCode=ArrayUtils.delete(0, singleCode);
								break;
							case "order_s_nhsp_code":
								bean.setNhspCode(nhspCode[0]);nhspCode=ArrayUtils.delete(0, nhspCode);
								break;
							case "order_s_wxsp_code":
								bean.setWxspCode(wxspCode[0]);wxspCode=ArrayUtils.delete(0, wxspCode);
								break;
							case "order_s_cust_po_no":
								bean.setCustPoNo(custPoNo[0]);custPoNo=ArrayUtils.delete(0, custPoNo);
								break;
							case "order_s_remark":
								bean.setRemark(remark[0]);remark=ArrayUtils.delete(0, remark);
								break;
							case "order_s_glasses_type":
								bean.setGlassesType(glassesType[0]);glassesType=ArrayUtils.delete(0, glassesType);
								break;
							case "order_s_light_trans":
								bean.setLightTrans(lightTrans[0]);lightTrans=ArrayUtils.delete(0, lightTrans);
								break;
							case "order_s_location":
								bean.setLocation(location[0]);location=ArrayUtils.delete(0, location);
								break;
							case "order_s_other_color":
								bean.setOtherColor(otherColor[0]);otherColor=ArrayUtils.delete(0, otherColor);
								break;
							case "order_s_content":
								bean.setContent(content[0]);content=ArrayUtils.delete(0, content);
								break;
							case "order_s_size":
								bean.setSize(size[0]);size=ArrayUtils.delete(0, size);
								break;
							case "order_s_quality_type":
								bean.setQualityType(qualityType[0]);qualityType=ArrayUtils.delete(0, qualityType);
								break;
							case "order_s_font":
								bean.setFont(font[0]);font=ArrayUtils.delete(0, font);
								break;
							case "order_s_arts":
								bean.setArts(arts[0]);arts=ArrayUtils.delete(0, arts);
								break;
							case "order_s_dqs":
								bean.setDqs(dqs[0]);dqs=ArrayUtils.delete(0, dqs);
								break;
							case "order_s_tys":
								bean.setTys(tys[0]);tys=ArrayUtils.delete(0, tys);
								break;
							case "order_s_yzs":
								bean.setYzs(yzs[0]);yzs=ArrayUtils.delete(0, yzs);
								break;
							case "order_s_dh_total"://大货数量
								bean.setDhTotal((order_s_dh_total[0].trim().length()>0)?order_s_dh_total[0]:"0");order_s_dh_total=ArrayUtils.delete(0, order_s_dh_total);
								bean.setDhDate(special_dh_date[materialTypeIndex].split(",")[specialDhDateLengthIndex]);
								specialDhDateLengthIndex++;
								if(specialDhDateLengthIndex>special_dh_date[materialTypeIndex].split(",").length-1) {
									specialDhDateLengthIndex=0;
								}
								break;
							default:
								break;
							}
					}
					bean.setLineNo(lineNo[i]);
					//投料数外部有 取外部 外部没有取内部
					if(bean.getSmallFeedTotal()!=null) {//内部有投料数
						bean.setFeedTotal(bean.getSmallFeedTotal());
					}else if(feedTotal!=null&&feedTotal.length>((materialTypeIndex>0)?lineNo.length+i:i)) {//内部没有 外部有
						/*此处为物料大组件一二都有外部投料数情况*/
						bean.setFeedTotal(feedTotal[(materialTypeIndex>0)?lineNo.length+i:i].trim().length()>0?feedTotal[(materialTypeIndex>0)?lineNo.length+i:i]:null);
					}else if(feedTotal!=null&&"投料数".equals(materialType[(materialTypeIndex>0)?listArrStrList.get(0).size()+j:j])){
						/*此处为物料大组件一或则二有外部投料数情况*/
						bean.setFeedTotal(feedTotal[i].trim().length()>0?feedTotal[i]:null);
					}else {//内部外部都没有
						bean.setFeedTotal(bean.getSmallFeedTotal());
					}
					//订单数外部有 取外部 外部没有取内部
					if(bean.getSmallOrderTotal()!=null) {//内部有订单数
						bean.setOrderTotal(bean.getSmallOrderTotal());
					}else if(orderTotal!=null&&orderTotal.length>((materialTypeIndex>0)?lineNo.length+i:i)) {//内部没有订单数  外部有 
						/*此处为物料大组件一二都有外部订单数情况*/
						bean.setOrderTotal(orderTotal[(materialTypeIndex>0)?lineNo.length+i:i].trim().length()>0?orderTotal[(materialTypeIndex>0)?lineNo.length+i:i]:null);
					}else if(orderTotal!=null&&"订单数".equals(materialType[(materialTypeIndex>0)?listArrStrList.get(0).size()+j:j])){
						/*此处为物料大组件一或则二有外部订单数情况*/
						bean.setOrderTotal(orderTotal[i].trim().length()>0?orderTotal[i]:null);
					}else {//内外都没有
						bean.setOrderTotal(bean.getSmallOrderTotal());
					}
					
					bean.setOrderNo(orderNo);
					if(materialFactory==null) {//旧模版默认为原材料仓
						bean.setMaterialFactory("1");
					}else {
						//bean.setMaterialFactory(materialFactory[j]);
						bean.setMaterialFactory(materialFactory[(materialTypeIndex>0)?listArrStrList.get(0).size()+j:j]);
					}
					//bean.setMaterialType(materialType[j]);
					bean.setMaterialType(materialType[(materialTypeIndex>0)?listArrStrList.get(0).size()+j:j]);
					/*if (isReadColor!=null&&isReadColor[(materialTypeIndex>0)?listArrStrList.get(0).size()+j:j].trim().length()>0) {
						//bean.setIsReadColor(Integer.valueOf(isReadColor[j]));
						bean.setIsReadColor(Integer.valueOf(isReadColor[(materialTypeIndex>0)?listArrStrList.get(0).size()+j:j]));
					}*/
					//校验是否为0 避免新模板保存的时候出现的问题
					if(bean.getIsReadColor()==0) {
						map.put("material_type", bean.getMaterialType());
						map.put("material_factory", bean.getMaterialFactory());
						Map<String, String> materialTypeInfo = orderCreateMapperNoApply.getMaterialTypeInfo(map);
						bean.setIsReadColor(Integer.valueOf(materialTypeInfo.get("isReadColor")));
					}
					bean.setApplyId(map.get("apply_id").toString());
					if(lineNoCodeMap!=null) {
						//通过物料代码补全物料信息
						fixMaterialInfo(bean,lineNoCodeMap,map);
					}
					list.add(bean);
				}
			}
		}
		
		/*int index = 0;
		for(int i=0;i<lineNo.length;i++) {
			for(int j=0;j<tableSourceArr.length;j++) {
				int index_data=i*tableSourceArr.length+j;
				bean = new OrderInfoDetailBean();
				bean.setColor(materialColor[index_data]);
				bean.setColorDescription(materialColorDescription[index_data]);
				bean.setFeedTotal(feedTotal[i]);
				bean.setLineNo(lineNo[i]);
				bean.setMaterialCode(materialCode[index_data]);
				bean.setMaterialFactory("1");
				if("2".equals(tableSourceArr[j])){//无规格
					bean.setMaterialModel("");
				}else{
					bean.setMaterialModel(materialModel[index]);
					index++;
				}
				bean.setMaterialType(materialType[j]);
				bean.setOrderNo(orderNo);
				bean.setOrderTotal(orderTotal[i]);
				System.out.println(bean);
				list.add(bean);
			}
		}*/
		return list;
	}

	//获取固定值
	public Map<String, String> getOrderInfoFixed(Map map) {
		// TODO Auto-generated method stub
		map = orderCreateMapper.getOrderInfoFixed(map);
		return map;
	}
	//获取固定值
	public Map<String, String> getOrderApplyId() {
		return orderCreateMapper.getOrderApplyId();
	}

	public JSONObject getOrderInfoForTemp(Map<String, String> map) {
		Map<String,String> map_orderInfo = orderCreateMapper.getOrderInfoByOrderNo(map.get("order_no").toString(),map.get("apply_id").toString());
		List<Map<String, Object>> map_orderInfoDetail =orderCreateMapper.getOrderInfoDetailByOrderNo(map.get("order_no").toString(),map.get("apply_id").toString());
		List<Map<String, Object>> map_orderInfoTail =orderCreateMapper.getOrderInfoTailByOrderNo(map.get("order_no").toString(),map.get("apply_id").toString());
		Map<String,String> map_orderCustomTag = orderCreateMapper.getOrderCustomTagByOrderNo(map.get("order_no").toString(),map.get("apply_id").toString());

		JSONObject object = new JSONObject();
		object.put("orderInfo", map_orderInfo);//订单信息主表
		object.put("orderInfoDetail", map_orderInfoDetail);//订单信息明细表
		if (map.get("sort_order_s_input_material_type")!=null) {
			List<Map<String, Object>> sort_map_orderInfoTail=getSortMapOrderInfoTail(map,map_orderInfoTail);
			object.put("orderInfoTail", sort_map_orderInfoTail);
		}else {
			object.put("orderInfoTail", map_orderInfoTail);
		}
		object.put("orderCustomTag", map_orderCustomTag);
		//大货时间
		String specialDhDate="";
		for(int i =0;i<map_orderInfoDetail.size();i++) {
			//第一行并且有大货时间
			if(map_orderInfoDetail.get(i).get("special_dh_date").toString().trim().length()>0&&"1".equals(map_orderInfoDetail.get(i).get("order_s_line_no").toString())) {
				specialDhDate+=map_orderInfoDetail.get(i).get("special_dh_date")+",";
			}
		}
		object.put("special_dh_date", (specialDhDate.length()>0)?specialDhDate.substring(0,specialDhDate.length()-1):specialDhDate);
		
		return object;
	}
	/*
	 * 流程卡特有 sort_order_s_input_material_type
	 * 通过排序避免数据顺序问题导致流程卡数据赋值出现顺序问题
	 * */
	private List<Map<String, Object>> getSortMapOrderInfoTail(Map<String, String> map,List<Map<String, Object>> source_map_orderInfoTail) {
		List<Map<String, Object>> sort_map_orderInfoTail = new ArrayList<>();
		String[] order_s_input_material_house_arr=map.get("order_s_input_material_house").toString().split(",");
		String[] order_s_input_material_type_arr =map.get("order_s_input_material_type").toString().split(",");
		Map<String, Object> temp_map=null;
		for(int i=0;i<order_s_input_material_house_arr.length;i++) {
			temp_map=new HashMap<>();
			temp_map.put("order_s_input_material_code", " ");
			temp_map.put("order_s_input_material_house", order_s_input_material_house_arr[i]);
			temp_map.put("order_s_input_material_type", order_s_input_material_type_arr[i]);
			temp_map.put("order_s_input_val_material_type", "");
			sort_map_orderInfoTail.add(i,temp_map);
			for(Map<String, Object> source_map:source_map_orderInfoTail) {
				if (source_map.get("order_s_input_material_house").toString().equals(order_s_input_material_house_arr[i].toString())
						&&
						source_map.get("order_s_input_material_type").toString().equals(order_s_input_material_type_arr[i].toString())	) {
					//System.out.println(source_map.get("order_s_input_material_type").toString());
					sort_map_orderInfoTail.remove(i);
					sort_map_orderInfoTail.add(source_map);
					break;
				}
			}
		}
		
		return sort_map_orderInfoTail;
	}

	public int checkTempAndOrderNo(Map<String, Object> map) {
		return orderCreateMapper.checkTempAndOrderNo(map);
	}
	//更新订单 --审核订单使用
	public int updateAudit(Map map) {
		// TODO Auto-generated method stub
		if("1".equals(map.get("order_p_audit").toString())) {
			map.put("order_p_audit", "1");
			map.put("order_p_order_status", "审核");
		}else if("0".equals(map.get("order_p_audit").toString())){
			map.put("order_p_audit", "0");
			map.put("order_p_order_status", "计划");
		}else{
			map.put("order_p_audit", "-1");
			map.put("order_p_order_status", "退回");
		}
		return orderCreateMapper.updateAudit(map);
	}
	
	public int deleteTemplate(Map<String, Object> map) {
		return orderCreateMapper.deleteTemplate(map);
	}
	//获取部门信息表
	public List<Map> selectOnlineByType(Map map) {
		// TODO Auto-generated method stub
		if("order_p_deptid".equals(map.get("type"))) {
			return orderCreateMapper.selectOnlineByDeptId(map);
		}
		if("order_p_product_work_no".equals(map.get("type"))) {
			return orderCreateMapper.selectOnlineForproductWorkNo(map);
		}
		return null;
	}
	//通过参数获取生产订单主表数据
	public List<Map> getOrderInfoByParam(Map map) {
		// TODO Auto-generated method stub
		return orderCreateMapper.getOrderInfoByParam(map);
	}
	//保存my_apply信息数据
	public boolean saveAsApplyInfo(Map<String, Object> map) {
		// TODO Auto-generated method stub
		int total = orderCreateMapper.saveAsApplyInfo(map);
		//发送申请消息
		sendTemplateMsg("apply",map);
		/**
		 * 物料信息修改改为后台判断
		 */
		List<OrderInfoDetailSourceAndApplyBean> beans = orderCreateMapper.getMaterialInfoForSourceAndApply(map);
		//查询相同该订单号和该申请id 同序号 同物料类型 同仓位的 数据 校验是否需要退回判断
		String msg = checkDiffMaterialInfo(beans,map.get("apply_id").toString(),map,false);
		if(total>0)return true;
		return false;
	}

	public void UpdateApplyInfo(Map map) {
		orderCreateMapper.updateApplyInfo(map);
	}
	//保存myaudit信息
	public Map<String, String> saveAsAuditInfo(Map map) {
		Map<String, String> msgMap = new HashMap<>();
		//判断订单是否已经审核
		if(orderCreateMapper.getAuditTotalByApplyId(map)>0) {
			msgMap.put("msg", "订单已经审核,请勿重复提交");
			return msgMap;
		}
		if("1".equals(map.get("status").toString())) {
			//判断数据是否合法
			//1&TR肶&1|2&TR肶&1| 序号&物料&仓位|
			/*String  specialRemarkStr = map.get("special_remark").toString();
			if(specialRemarkStr.length()>0) {
				specialRemarkStr=specialRemarkStr.substring(0,specialRemarkStr.length()-1);
				String[] specialRemarkArr = specialRemarkStr.split("\\|");
				String retStr="";
				for(int i=0;i<specialRemarkArr.length;i++) {
					String[] specialRemark=specialRemarkArr[i].split("&");
					if(specialRemark[0].equals("all")) {
						if(orderCreateMapper.selectFeedOrderDetail(specialRemark[0],specialRemark[1],specialRemark[2],map.get("order_no").toString())>0) {
							retStr+="请先检查订单号["+map.get("order_no").toString()+"]有物料未退回仓库";
						}
					}else {
						if(orderCreateMapper.selectFeedOrderDetail(specialRemark[0],specialRemark[1],specialRemark[2],map.get("order_no").toString())>0) {
							retStr+="请先检查订单号["+map.get("order_no").toString()+"]序号["+specialRemark[0]+"]物料["+specialRemark[1]+"]有物料未退回\r\n";
						}
					}
				}
				if(retStr.length()>0) {
					msgMap.put("msg", retStr);
					return msgMap;
				}
			}*/
			//物料信息修改改为后台判断
			List<OrderInfoDetailSourceAndApplyBean> beans = orderCreateMapper.getMaterialInfoForSourceAndApply(map);
			//查询相同该订单号和该申请id 同序号 同物料类型 同仓位的 数据 校验是否需要退回判断
			String msg = checkDiffMaterialInfo(beans,map.get("apply_id").toString(),map,true);
			if(msg.length()>0) {
				msgMap.put("msg", msg);
				return msgMap;
			}
			
			//数据转移
			//元数据表移动到_audit
			orderCreateMapper.insertOrderInfoTemplateSourceToAudit(map);
			orderCreateMapper.insertOrderTemplateLinkSourceToAudit(map);
			orderCreateMapper.insertOrderInfoCustomTagSourceToAudit(map);
			orderCreateMapper.insertOrderInfoTailSourceToAudit(map);
			orderCreateMapper.insertOrderInfoDetailSourceToAudit(map);
			orderCreateMapper.insertOrderInfoPrimarySourceToAudit(map);
			//删除元数据表
			orderCreateMapper.deleteOrderInfo(map.get("order_no").toString());
			orderCreateMapper.deleteOrderInfoAndTemplate(map.get("order_no").toString());
			//将申请表写入元数据表
			orderCreateMapper.insertOrderInfoTemplateApplyToSource(map);
			map.put("order_template_id", map.get("id").toString());
			orderCreateMapper.insertOrderTemplateLinkApplyToSource(map);
			orderCreateMapper.insertOrderInfoCustomTagApplyToSource(map);
			orderCreateMapper.insertOrderInfoTailApplyToSource(map);
			orderCreateMapper.insertOrderInfoDetailApplyToSource(map);
			orderCreateMapper.insertOrderInfoPrimaryApplyToSource(map);
		}else {
			fileManagerMapper.updateLastOneStatusByOrderNo(map.get("order_no").toString(), "0");
		}
		orderCreateMapper.saveAsAuditInfo(map);
		orderCreateMapper.updateApplyInfo(map);
		msgMap.put("msg", "数据审核成功");
		//发送审核消息
		sendTemplateMsg("audit",map);
		return msgMap;
	}
	//校验车间数量
	public String checkDiffWorkShopTotal(OrderInfoDetailSourceAndApplyBean bean,Boolean materialIsUpdate) {
		// TODO Auto-generated method stub
		//20190401不再车间数量检查限制 
		return "";
		/*ReportBean reportBean = new ReportBean();
		reportBean.setOrderId(bean.getOrderNo());//订单编号
		reportBean.setMachining(bean.getMaterialType());//物料类型
		reportBean.setRowIndex(bean.getLineNo());//行号
		//得到在车间的数量
		long count = workshopService.getOrderAllWorkShopTurnoverCount(reportBean);
		if(count > Float.valueOf(bean.getApplyFeedTotal()) || (count>0&&materialIsUpdate)) {
			//如果在车间数量大于申请数量则退回 ["+(count - Float.valueOf(bean.getApplyFeedTotal()))+"]
			if(bean.getMaterialCode()!=null&&bean.getMaterialCode().trim().length()>0) {//必须要求有物料代码 车间才能退回
				return "请先检查订单号["+bean.getOrderNo()+"]序号["+bean.getLineNo()+"]物料["+bean.getMaterialType()+"]还需从车间退回仓库\r\n";
			}else {
				return "";
			}
		}
		return "";*/
	}
	//校验物料是否修改并查询
	/**
	 * 校验逻辑
	 * @param beans
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String checkDiffMaterialInfo(List<OrderInfoDetailSourceAndApplyBean> beans,String applyId,Map map,boolean returnFeedOrder) {
		String msg ="";
		String specialRemark="";
		OrderInfoDetailSourceAndApplyBean bean = null;
		for (int i = 0; i < beans.size(); i++) {
			bean=beans.get(i);
			/**
			 * 订单审核通过条件
			 * 必须满足所有物料申请投料数等于物料在车间数(申请投料数小于物料在车间数 需要车间退回,申请投料数大于物料在车间数 需要投料单退回)
			 * 并且物料信息(色号,色号描述,规格型号,物料名称)如果修改必须退回投料单
			 * 原 Integer.valueOf(bean.getFeedTotal())>Integer.valueOf(bean.getApplyFeedTotal())不符合实际场景
			 */
			/*if(true) {
				//判断是否生产投料单  调用卢叶峰的方法
				ReportBean reportBean = new ReportBean();
				reportBean.setOrderId(bean.getOrderNo());//订单编号
				reportBean.setMachining(bean.getMaterialType());//物料类型
				reportBean.setRowIndex(bean.getLineNo());//行号
				//得到在车间的数量
				long count = workshopService.getOrderAllWorkShopTurnoverCount(reportBean);
				if(count > Float.valueOf(bean.getApplyFeedTotal())) {
					//如果在车间数量大于申请数量则退回
					msg+="请先检查订单号["+bean.getOrderNo()+"]序号["+bean.getLineNo()+"]物料["+bean.getMaterialType()+"]还需从车间退回仓库["+(count - Float.valueOf(bean.getApplyFeedTotal()))+"]\r\n";
				}
			}*/
			
			//用料条数修改
			if(!bean.getYltsTotal().equals(bean.getApplyYltsTotal())){
				//用料条数修改修改了判断投料单是否退回
				Map<String, Object> feedOrderDetailMap = orderCreateMapper.selectFeedOrderDetail(bean.getLineNo(),bean.getMaterialType(),bean.getMaterialFactory(),bean.getOrderNo());
				if(feedOrderDetailMap!=null&&Integer.valueOf(feedOrderDetailMap.get("total").toString())>0) {
					//msg+="2请先检查订单号["+bean.getOrderNo()+"]序号["+bean.getLineNo()+"]物料["+bean.getMaterialType()+"]有物料投料单未退回\r\n";
					if(returnFeedOrder) {
						this.updateMaterialInfoThenCreateFeedOrderDetail("3",map.get("loginUserId").toString(),
								map.get("loginCompany").toString(),
								map.get("loginUserName").toString(),
								feedOrderDetailMap.get("feenOrderDetailId").toString());
					}
					specialRemark+=bean.getLineNo()+"&"+bean.getMaterialType()+"&"+bean.getMaterialFactory()+"|";
				}
				continue;	
			}
			//先物料代码是否一样 
			if(bean.getMaterialCode().trim().length()>0) {
				//有物料代码如果物料代码不同
				if(!bean.getMaterialCode().equals(bean.getApplyMaterialCode())) {
					//物料信息修改了判断投料单是否退回
					Map<String, Object> feedOrderDetailMap = orderCreateMapper.selectFeedOrderDetail(bean.getLineNo(),bean.getMaterialType(),bean.getMaterialFactory(),bean.getOrderNo());
					if(feedOrderDetailMap!=null&&Integer.valueOf(feedOrderDetailMap.get("total").toString())>0) {
						//msg+="2请先检查订单号["+bean.getOrderNo()+"]序号["+bean.getLineNo()+"]物料["+bean.getMaterialType()+"]有物料投料单未退回\r\n";
						if(returnFeedOrder) {
							this.updateMaterialInfoThenCreateFeedOrderDetail("3",map.get("loginUserId").toString(),
									map.get("loginCompany").toString(),
									map.get("loginUserName").toString(),
									feedOrderDetailMap.get("feenOrderDetailId").toString());
						}
						specialRemark+=bean.getLineNo()+"&"+bean.getMaterialType()+"&"+bean.getMaterialFactory()+"|";
					}
					//校验车间数量
					msg+=checkDiffWorkShopTotal(bean,true);
					continue;
				}
			}

			//||!bean.getMaterialName().equals(bean.getApplyMaterialName() 暂时去掉物料名称判断
			//||!bean.getColorDescription().equals(bean.getApplyColorDescription()) 暂时去掉物料颜色描述判断
			if(bean.getMaterialCode().trim().length()==0){
				//无物料代码 物料信息不同
				if (!bean.getColor().equals(bean.getApplyColor())
						||!bean.getMaterialModel().equals(bean.getApplyMaterialModel())
						) {
					//物料信息修改了判断投料单是否退回
					Map<String, Object> feedOrderDetailMap = orderCreateMapper.selectFeedOrderDetail(bean.getLineNo(),bean.getMaterialType(),bean.getMaterialFactory(),bean.getOrderNo());
					if(feedOrderDetailMap!=null&&Integer.valueOf(feedOrderDetailMap.get("total").toString())>0) {
						//msg+="3请先检查订单号["+bean.getOrderNo()+"]序号["+bean.getLineNo()+"]物料["+bean.getMaterialType()+"]有物料投料单未退回\r\n";
						if(returnFeedOrder) {
							this.updateMaterialInfoThenCreateFeedOrderDetail("3",map.get("loginUserId").toString(),
									map.get("loginCompany").toString(),
									map.get("loginUserName").toString(),
									feedOrderDetailMap.get("feenOrderDetailId").toString());
						}
						specialRemark+=bean.getLineNo()+"&"+bean.getMaterialType()+"&"+bean.getMaterialFactory()+"|";
					}
					//校验车间数量
					msg+=checkDiffWorkShopTotal(bean,true);
					continue;
				}
			}
			
			//仅仅投料数修改
			if(!Integer.valueOf(bean.getFeedTotal()).equals(Integer.valueOf(bean.getApplyFeedTotal()))){
				//物料信息修改了判断投料单是否退回
				Map<String, Object> feedOrderDetailMap = orderCreateMapper.selectFeedOrderDetail(bean.getLineNo(),bean.getMaterialType(),bean.getMaterialFactory(),bean.getOrderNo());
				if(feedOrderDetailMap!=null&&Integer.valueOf(feedOrderDetailMap.get("total").toString())>0) {
					//msg+="1请先检查订单号["+bean.getOrderNo()+"]序号["+bean.getLineNo()+"]物料["+bean.getMaterialType()+"]有物料投料单未退回\r\n";
					if(returnFeedOrder) {
						this.updateMaterialInfoThenCreateFeedOrderDetail("3",map.get("loginUserId").toString(),
								map.get("loginCompany").toString(),
								map.get("loginUserName").toString(),
								feedOrderDetailMap.get("feenOrderDetailId").toString());
					}
					specialRemark+=bean.getLineNo()+"&"+bean.getMaterialType()+"&"+bean.getMaterialFactory()+"|";
				}
				//校验车间数量
				msg+=checkDiffWorkShopTotal(bean,false);
				continue;	
			}
		}
		//更新specialRemark
		if (!"".equals(specialRemark)) {
			orderCreateMapper.updateApplySpecialRemark(specialRemark,applyId);
		}
		return msg;
	}
	/**
	 * 修改物料信息则老的投料单退回然后老的采购单显示退回按钮 并有一条新的未生成投料单的数据
	 */
	public void updateMaterialInfoThenCreateFeedOrderDetail(String status,String userId,String loginCompany,String userName,String feedOrderDetailId) {
		/**approval/allApprovalFeedOrder
		beanArray: [{"id":"2019040119411434446b83c056f4b452185bc7368c8f392f7","approvalReason":"嘎嘎"}]
		status: 3
		**/
		Map map = new HashMap<>();
		map.put("status", status);// 3 退回
		map.put("loginUserId", userId);
		map.put("loginCompany", loginCompany);
		map.put("loginUserName", userName);
		JSONArray jsonArray = new JSONArray();
		JSONObject object = new JSONObject();
		object.put("id", feedOrderDetailId);
		object.put("approvalReason", "系统自动退回审核");
		jsonArray.add(object);
		map.put("beanArray", jsonArray.toString());
		//查询有没有采购单
		FeedOrderDetailBean feedOrderDetailBean = orderMapper.getFeedOrderDetailOneById(feedOrderDetailId);
		if (feedOrderDetailBean.getIsBuild().equals(1)) {
			Map<String, Object> mapPurchaseOrder = new HashMap<>();
			mapPurchaseOrder.put("feedDetailId", feedOrderDetailBean.getId());
			mapPurchaseOrder.put("loginCompany", loginCompany);
			String purchaseDetailId = orderCreateMapper.getPurchaseOrderDetailIdByFeedDetailId(mapPurchaseOrder);
			//throw new ServiceException("该投料单已生成采购单,请打生产订单修改单后,退回采购单 订单编号 :" + orderId);
			//校验采购单能否直接退回 库存可用数-（取消订单的采购数-占用数）< 0  
			feedOrderService.checkPurchaseOrderApprovalBack(purchaseDetailId,1,loginCompany);
			Map<String, String> approvalPurchaseOrderMap = new HashMap<>();
			approvalPurchaseOrderMap.put("purchaseDetailId", purchaseDetailId);
			approvalPurchaseOrderMap.put("type", "1");
			approvalPurchaseOrderMap.put("name", userName);
			approvalPurchaseOrderMap.put("orderId", feedOrderDetailBean.getOrderId());
			approvalPurchaseOrderMap.put("approvalReason", "物料信息修改系统自动退回");
			approvalPurchaseOrderMap.put("loginUserId", map.get("loginUserId").toString());
			approvalPurchaseOrderMap.put("loginUserName", map.get("loginUserName").toString());
			approvalPurchaseOrderMap.put("loginCompany",  map.get("loginCompany").toString());
			purchaseOrderService.approvalPurchaseOrder(approvalPurchaseOrderMap,2);
			return;
		}
		orderService.allApprovalFeedOrder(map);
	}
	
	//通过订单编号获取申请审核备注信息
	public List<Map> getRemarkData(Map map) {
		return orderCreateMapper.getRemarkData(map);
	}
	
	//发送模版推送消息
	public void sendTemplateMsg(String action,Map map) {
		//避免推送消息出现问题导致订单审核和保存出现回滚
		try {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	        String time = simpleDateFormat.format(new Date());
	        String accessToken=weiXinService.getAccessToken(null);
	        String audit_type="1";//订单审核
	        String remarkInfo="";//推送备注
	        //通过系统编号查询订单信息
	        OrderBean orderBean = orderMapper.getOrderByOrderId(map.get("order_no").toString());
	        remarkInfo+="订单编号["+orderBean.getCompanyOrderId()+"] ";
	        if("apply".equals(action)) {
				//查询订单申请审核人openid
	        	String applyPhone="";
				List<Map<String, String>> list=orderCreateMapper.getOpenIdForAudit(map.get("loginUserId").toString(),audit_type);
				for(int i=0;i<list.size();i++) {
					applyPhone=list.get(i).get("phone");
					JSONObject data =WeixinTemplateList.packJsonWatiApproval("您有待审核的任务，请电脑端审核。", 
							"订单申请审核", map.get("loginUserName").toString(), 
							list.get(i).get("phone"),time , remarkInfo+"工厂型号["+map.get("order_p_product_no").toString()+"]申请需要审核", "", null, null, null, null, null, null, null);
					//WeiXinParamesUtil.messageLink+"?loginToken="+list.get(i).get("openid")+"&pageType="+RedirectUrlUtil.orderApplyAudit+"?order_p_order_no_sys="+orderBean.getOrderId()
					WeixinTemplateSender.sendWechatmsgToUser(list.get(i).get("openid"), "Ugl14MUqyvpWkHZPm9wuju_1tC_68FoLYfPV2muCvD0", "", data, accessToken);
				}
				//通知额外的人
				List<String> userIds = weChatToMessageService.getWeChatNewsUserIdListByParam(map.get("loginCompany").toString(), null, null, "6");
				if (userIds.size()<1) {//没有额外的人的时候
					return;
				}
				List<Map<String, String>> other_list = orderCreateMapper.getInfoForWeixinTemplate(userIds);
				for(int i=0;i<other_list.size();i++) {
					JSONObject data =WeixinTemplateList.packJsonWatiApproval("您有待审核的任务，请电脑端审核。", 
							"订单申请审核", map.get("loginUserName").toString(), 
							applyPhone,time ,remarkInfo+"工厂型号["+map.get("order_p_product_no").toString()+"]申请需要审核", "", null, null, null, null, null, null, null);
					// WeiXinParamesUtil.messageLink+"?loginToken="+list.get(i).get("openid")+"&pageType="+RedirectUrlUtil.orderApplyAudit+"?order_p_order_no_sys="+orderBean.getOrderId()
					WeixinTemplateSender.sendWechatmsgToUser(other_list.get(i).get("openid"), "Ugl14MUqyvpWkHZPm9wuju_1tC_68FoLYfPV2muCvD0","", data, accessToken);
				}
			}
			if("audit".equals(action)) {
				//查询订单申请人ID
				List<String> list=orderCreateMapper.getOpenIdForApply(map.get("order_no").toString());
				for(int i=0;i<list.size();i++) {
					String audit_statut= ("1".equals(map.get("status").toString()))?"审核通过":"审核不通过";
					String auditor= map.get("loginUserName").toString();
					JSONObject data =WeixinTemplateList.packJsonToApplyStatus(remarkInfo+"工厂型号["+map.get("order_p_product_no").toString()+"]",audit_statut, auditor, time, "请电脑登录查询.",  null, null, null, null, null);
					WeixinTemplateSender.sendWechatmsgToUser(list.get(i), "YZ-XYrfpgePDfNxSxQRrnzPiy35C_ypXi8Iwe3enbiQ", WeiXinParamesUtil.messageLink+"?loginToken="+list.get(i)+"&pageType="+RedirectUrlUtil.orderApplyAudit+"?order_p_order_no_sys="+orderBean.getOrderId(), data, accessToken);
				}			
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	/**
	 * 将序号物料代码转换成code
	 * @param map
	 * @return
	 */
	public Map<String,String> getLineNoCode(Map map){
		Map<String,String> lineNoCode = null;
		if(map.get("line_no_material_code")!=null&&map.get("line_no_material_code").toString().trim().length()>0) {
			lineNoCode = new HashMap<>();
			String[] lineNoCodeArr = map.get("line_no_material_code").toString().split(",");
			for(int i=0 ;i<lineNoCodeArr.length;i++) {
				String[] lineNoCodeStr=lineNoCodeArr[i].split("@");
				if(lineNoCodeStr.length==2) {
					lineNoCode.put(lineNoCodeStr[0], lineNoCodeStr[1]);
				}else {
					lineNoCode.put(lineNoCodeStr[0], "");
				}
			}
		}
		return lineNoCode;
	}
	/**
	 * 补全物料信息 通过物料表
	 */
	public  void fixMaterialInfo(OrderInfoDetailBean bean,Map lineNoCode, Map requestMap) {
		//拼接key 序号|物料类型|仓位
		String  key = bean.getLineNo()+"|"+bean.getMaterialType()+"|"+bean.getMaterialFactory();
		//通过lineNoCode获取物料代码
		if(lineNoCode.get(key)!=null&&lineNoCode.get(key).toString().trim().length()>0) {
			String materialCode = lineNoCode.get(key).toString().trim();
			//获取物料信息
			OrderInfoDetailBean beanByCode = orderCreateMapperNoApply.getMaterialInfoByCode(materialCode,requestMap);
			if(beanByCode!=null) {
				bean.setMaterialCode(beanByCode.getMaterialCode());//物料代码
				if(1==bean.getIsReadColor()) {
					if (bean.getIsReadColor()==0) {
						bean.setIsReadColor(1);
					}
					bean.setColor(beanByCode.getColor());//色号
					//bean.setColorDescription(beanByCode.getColorDescription());//描述
				}else {
					if (bean.getIsReadColor()==0) {
						bean.setIsReadColor(2);
					}
				}
				bean.setMaterialModel(beanByCode.getMaterialModel());//规格
				bean.setMaterialName(beanByCode.getMaterialName());//物料名称
			}
		}
		
	}
	/**
	 * 单位转换计算 统一转为物料信息的单位
	 * @param list 退回多条 包含数量和单位
	 * @param bean 投料数和单位
	 * @param map  投料单明细转换之后数量和
	 * @return
	 */
	public BigDecimal changeUnit(List<Map> list,OrderInfoDetailSourceAndApplyBean bean,Map map){
		BigDecimal returnTotal=new BigDecimal(0);
		for (int i = 0; i < list.size(); i++) {
			String backUnit = list.get(i).get("unit").toString();
			String backTotal = list.get(i).get("total").toString();
			if(backUnit.equals(bean.getUnit())) {//订单单位默认是 付
				//单位相等
				returnTotal = new BigDecimal(backTotal).add(returnTotal);
			}else {
				//单位不相等 进行换算
				//   退回数/投料单数量*订单投料数
				returnTotal = new BigDecimal(backTotal).divide(new BigDecimal(map.get("feedCount").toString()),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(bean.getFeedTotal())).add(returnTotal);
			}
		}
		return returnTotal;
	}
	/**
	 *  获取dialog选择物料total
	 * @param map
	 * @return
	 */
	public int getFactoryTabChildListTotal(Map<String, String> map) {
		// TODO Auto-generated method stub
		return orderCreateMapperNoApply.getFactoryTabChildListTotal(map);
	}
}
